package cc.vv.btpartyjob.partyservice.activity

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Message
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.global.BCBroadCastKey
import cc.vv.baselibrary.global.BCFileBasePath
import cc.vv.baselibrary.http.BaseHttpRequest
import cc.vv.baselibrary.util.ChooserHeadImg
import cc.vv.baselibrary.util.LKTimeUtil
import cc.vv.baselibrary.util.LKToastUtil
import cc.vv.baselibrary.util.ParseFilePath
import cc.vv.baselibrary.view.BaseTopBarView
import cc.vv.baselibrary.view.imgselector.ImageSelector
import cc.vv.btpartyjob.jnimodule.api.JniModuleAPI
import cc.vv.btpartyjob.jnimodule.binder.BaseBinder
import cc.vv.btpartyjob.jnimodule.globle.IntentJniKey
import cc.vv.btpartyjob.jnimodule.moudel.resp.FileUpResponseObj
import cc.vv.btpartyjob.jnimodule.server.JniStartActivity
import cc.vv.btpartyjob.jnimodule.server.OperationServer
import cc.vv.btpartyjob.jnimodule.server.ResourceChooseServer
import cc.vv.btpartyjob.partyservice.R
import cc.vv.btpartyjob.partyservice.api.PartyServiceAPI
import cc.vv.btpartyjob.partyservice.delegate.AddVolunteerActivityDelegate
import cc.vv.btpartyjob.partyservice.module.bean.AddVolunteerObj
import cc.vv.btpartyjob.partyservice.module.resp.AddVolunteerResponseObj
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import cc.vv.mvp.activity.BaseActivityMVP
import cc.vv.mvp.binder.BaseDataBinder
import java.io.File

/**
 * 添加志愿者
 * Created by Chen.qi on 2018/10/29.
 */
class AddVolunteerActivity : BaseActivityMVP<AddVolunteerActivityDelegate>() {

    /**
     * 头像处理
     */
    var chooserHeadImg: ChooserHeadImg? = null
    /**
     * 头像用户名接收广播
     */
    private var mMyBroadCast: MyBroadCast? = null
    /**
     * 刷选器
     */
    var filter: IntentFilter? = null
    /**
     * 2.0获取的头像
     */
    private var imagesPath: ArrayList<String>? = null

    /**
     * 性别
     */
    private var sex: Int = 0

    /**
     * 头像
     */
    private var headPath: String? = null

    /**
     * 出生日期
     */
    private var birthDayTime: Long = 0

    /**
     * 志愿时间
     */
    private var volunteerTime: Long = 0

    /**
     * 志愿类型
     */
    private var volunteerType: String? = null

    private val strList = listOf("定时性", "临时性")


    /**
     * 所有路径地址
     */
    private var allPth: String? = null


    override fun initData() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        viewDelegate?.setTopBarTitle("添加志愿者")
        //初始化头像处理类
        chooserHeadImg = ChooserHeadImg(this)
        //初始化广播
        initBroadcast()
        viewDelegate?.selectedSex(true)
    }

    override fun bindEvenListener() {
        viewDelegate?.setTitleBackBtnOnClick(object : BaseTopBarView.EventInterface {
            //返回
            override fun leftOnClick() {
                finish()
            }

            override fun leftCloseClick() {}
            override fun rightOnClick() {
            }
        })

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //选择头像
            OperationServer.openPic(this)
        }, R.id.lkv_aadVo_headImg)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //男
            sex = 0
            viewDelegate?.selectedSex(true)
        }, R.id.ll_addVo_man)
        viewDelegate?.setOnClickListener(View.OnClickListener {
            //女
            sex = 1
            viewDelegate?.selectedSex(false)
        }, R.id.ll_addVo_woman)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //出生日期
            ResourceChooseServer.chooseData(this, handler, 11)
        }, R.id.ll_aadVo_birthDay)


        viewDelegate?.setOnClickListener(View.OnClickListener {
            //所属地区
            JniStartActivity.startIntentOrganActivity(this, 3, 3, 100, true)

        }, R.id.ll_aadVo_suoShuDiQu)


        viewDelegate?.setOnClickListener(View.OnClickListener {
            //志愿类型
            ResourceChooseServer.getWheelerWayDialog(this, "志愿类型", handler, 13, strList)

        }, R.id.ll_aadVo_volunteerType)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //志愿时间
            ResourceChooseServer.chooseData(this, handler, 12)


        }, R.id.ll_addVo_zhiYuanTime)

        viewDelegate?.setOnClickListener(View.OnClickListener {
            //提交
            val volunteerName = viewDelegate?.getVolunteerName()
            val volunteerZhiYe = viewDelegate?.getVolunteerZhiYe()
            val volunteerTeChang = viewDelegate?.getVolunteerTeChang()
            val volunteerPhone = viewDelegate?.getVolunteerPhone()
            val volunteerRemarkInfo = viewDelegate?.getVolunteerRemarkInfo()

            if (TextUtils.isEmpty(headPath)) {
                LKToastUtil.showToastShort("请上传头像")
                return@OnClickListener
            }

            if (TextUtils.isEmpty(volunteerName) || TextUtils.isEmpty(volunteerZhiYe) || TextUtils.isEmpty(volunteerTeChang)
                    || TextUtils.isEmpty(volunteerPhone) || TextUtils.isEmpty(volunteerType) || TextUtils.isEmpty(allPth) || birthDayTime < 1 || volunteerTime < 1) {
                LKToastUtil.showToastShort("请将信息录入完整")
                return@OnClickListener
            }

            val param = AddVolunteerObj()
            val split = allPth!!.split("-")
            if (split.size == 4) {
                param.street = split[1]
                param.community = split[2]
                param.grid = split[3]
            }
            param.faceUrl = headPath
            param.name = volunteerName
            param.sex = sex
            param.dateofbirth = birthDayTime
            param.career = volunteerZhiYe
            param.specialty = volunteerTeChang
            param.mobile = volunteerPhone
            param.volunteerType = volunteerType
            param.volunteerTime = volunteerTime
            param.remarks = volunteerRemarkInfo
            BaseHttpRequest.postRequest(PartyServiceAPI.addVolunteerUrl,
                    param, AddVolunteerResponseObj::class.java, true,
                    Settings(MediaTypeWrap.MEDIA_TYPE_RAW_JSON))
        }, R.id.rl_addVo_submit)


    }

    override fun getDelegateClass(): Class<AddVolunteerActivityDelegate> {
        return AddVolunteerActivityDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return BaseBinder()

    }


    override fun onHandleMsg(msg: Message?) {
        super.onHandleMsg(msg)
        when (msg?.what) {
            10 -> {
                //选择用户头像成功，上传头像到服务器
                val imgUrl = BCFileBasePath.PATH_CACHE_IMG + "/" + "yunjing" + "/" + BCFileBasePath.PATH_HEADIMG
                val uploadFile = ResourceChooseServer.uploadFile(imgUrl)
                if (null == uploadFile) {
                    LKToastUtil.showToastShort("头像上传失败")
                    return
                }
                val headPath = JniModuleAPI.uploadHeadHttp
                BaseHttpRequest.postFileRequest(headPath, uploadFile, FileUpResponseObj::class.java, true)
            }
            11 -> {
                //出生日期选择
                val time: String = msg.obj as String
                birthDayTime = LKTimeUtil.getInstance().getLongTime(time, "yyyy-MM-dd")
                viewDelegate?.setDataTime(time)
            }
            12 -> {
                //志愿时间日期
                val time: String = msg.obj as String
                volunteerTime = LKTimeUtil.getInstance().getLongTime(time, "yyyy-MM-dd")
                viewDelegate?.setVolunteerTime(time)
            }
            13 -> {
                //选择方式
                val wayString: String = msg.obj as String
                volunteerType = wayString
                viewDelegate?.setVolunteerType(wayString)

            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }

        if (requestCode == 100 && resultCode == 101) {
            allPth = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_PARENT_PATH)
            val allPthName = data.getStringExtra(IntentJniKey.INTENT_KEY_ORGAN_PARENT_ALL_NAME)
            viewDelegate?.setVolunteerDiQu(allPthName)

        } else {
            //这里设置头像回调
            chooserHeadImg?.onActivityResult(requestCode, resultCode, data, viewDelegate?.getHeadPic())
            //获取头像
            if (ImageSelector.REQUEST_SELECT_IMAGE == requestCode && resultCode == Activity.RESULT_OK) {
                imagesPath = data!!.getStringArrayListExtra(ImageSelector.SELECTED_RESULT)
                if (imagesPath!!.size > 0) {
                    val file = File(imagesPath?.get(0))
                    val uri = Uri.fromFile(file)
                    val _uri = ParseFilePath.getUri(this, uri)
                    chooserHeadImg?.startPhotoZoom(_uri, ChooserHeadImg.USERINFO_CLIP_REQUEST, this)
                }
            }
        }
    }


    /**
     * 广播接收
     */
    private inner class MyBroadCast : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            //接收头像修改广播，发送对应的消息
            if (intent != null && intent.action == BCBroadCastKey.BROADCAST_IMGHEAD_UPSUCCESS) {
                handler.sendEmptyMessage(10)
            }
        }
    }

    /**
     * 初始化广播（接收头像和用户名改变的广播）
     */
    private fun initBroadcast() {
        mMyBroadCast = MyBroadCast()
        filter = IntentFilter()
        filter?.addAction(BCBroadCastKey.BROADCAST_IMGHEAD_UPSUCCESS)
        this.registerReceiver(mMyBroadCast, filter)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != mMyBroadCast) {
            unregisterReceiver(mMyBroadCast)
        }
    }

    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        when (obj) {
            is FileUpResponseObj -> {
                //头像
                headPath = obj.data.url
            }
            is AddVolunteerResponseObj -> {
                LKToastUtil.showToastShort("志愿者添加成功")
                setResult(101)
                finish()
            }
        }
    }

    override fun getBadCode(obj: BaseResponseObj<*>?) {
        super.getBadCode(obj)
        LKToastUtil.showToastShort("网络异常")
    }


}